package util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import static util.Config.getCrawler_INVALID_WAIT_TIME;
import static util.CrawlSleepTime.sleep;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xalan.internal.xsltc.dom.CachedNodeListIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.selector.Json;

public class CookieUtil {

    private static final String URL=Config.getCrawler_COOKIE_POOL();
    public static Logger logger = LoggerFactory.getLogger(CookieUtil.class);

    public static final HashMap<String,String> getCookie(String proxyStrFormat){
        HashMap<String,String> cookie = new HashMap<String, String>();
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(URL);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("ip", proxyStrFormat));

        int statusCode = 0;
        try {
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            String dict = EntityUtils.toString(responseEntity);

            JSONObject j = JSON.parseObject(dict);
            if (responseEntity != null) {
                cookie.put("cookieContent",j.get("cookies").toString());
                cookie.put("cookieId",j.get("username").toString());
            }else {
                logger.error("账号池链接失败。");
            }
            statusCode = response.getStatusLine().getStatusCode();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return cookie;
    }
    public static final boolean invalidCookie(String cookieId,String ip,String href){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(Config.getCrawler_COOKIE_POOL_VER());
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("username", cookieId));
        params.add(new BasicNameValuePair("ip", ip));
        params.add(new BasicNameValuePair("href", href));
        int statusCode = 0;
        try {


            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            String dict = EntityUtils.toString(responseEntity);
            JSONObject j = JSON.parseObject(dict);
            if (Boolean.valueOf(j.get("result").toString()).equals(false)) {
                logger.info("账号池正在检验账户: "+cookieId+" ip: "+j.get("msg").toString());
                sleep(Integer.valueOf(getCrawler_INVALID_WAIT_TIME()));
            }else if (Boolean.valueOf(j.get("result").toString()).equals(true)){

                logger.info("账户: "+cookieId+" ip: "+ip+" 检验成功!");

            }
            statusCode = response.getStatusLine().getStatusCode();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (statusCode == 200){
            return true;
        }else {
            return false;
        }

    }
}
